<template>
    <div class="page-container" v-loading="loading">
        <el-page-header @back="goBack" :content="'订单交割: ' + (order.id || '')"></el-page-header>

        <el-card class="mt-4">
            <template #header>
                <div class="card-header">
                    <span>原始订单明细</span>
                    <el-tag :type="getStatusTag(order.status)">{{ getStatusText(order.status) }}</el-tag>
                </div>
            </template>
            <el-table :data="order.details" style="width: 100%" border>
                <el-table-column prop="id" label="明细ID"></el-table-column>
                <el-table-column prop="fundCode" label="基金代码"></el-table-column>
                <el-table-column prop="direction" label="方向"></el-table-column>
                <el-table-column prop="amount" label="计划金额"></el-table-column>
            </el-table>
        </el-card>

        <el-card class="mt-4">
            <template #header>
                <span>交割信息录入</span>
            </template>
            <el-form :model="settlementForm" ref="settlementFormRef" label-width="100px">
                <div v-for="(detail, index) in settlementForm.details" :key="detail.orderDetailId"
                    class="settlement-item">
                    <h4>基金: {{ getFundCodeByDetailId(detail.orderDetailId) }} (明细ID: {{ detail.orderDetailId }})</h4>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item :label="'成交金额'" :prop="'details.' + index + '.settledAmount'"
                                :rules="rules.settledAmount">
                                <el-input-number v-model="detail.settledAmount" :precision="2" :step="100" :min="0"
                                    style="width: 100%;"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item :label="'成交份额'" :prop="'details.' + index + '.settledShares'"
                                :rules="rules.settledShares">
                                <el-input-number v-model="detail.settledShares" :precision="4" :step="100" :min="0"
                                    style="width: 100%;"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item :label="'手续费'" :prop="'details.' + index + '.fee'" :rules="rules.fee">
                                <el-input-number v-model="detail.fee" :precision="2" :step="1" :min="0"
                                    style="width: 100%;"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item :label="'是否成功'" :prop="'details.' + index + '.success'">
                                <el-switch v-model="detail.success"></el-switch>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" v-if="!detail.success">
                            <el-form-item :label="'失败原因'" :prop="'details.' + index + '.failureReason'"
                                :rules="rules.failureReason">
                                <el-input v-model="detail.failureReason" type="textarea"
                                    placeholder="请输入失败原因"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <el-form-item>
                    <el-button type="primary" @click="submitSettlement" :loading="submitting">提交交割单</el-button>
                </el-form-item>
            </el-form>
        </el-card>

    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const route = useRoute();
const router = useRouter();

const order = ref({});
const loading = ref(true);
const submitting = ref(false);
const settlementFormRef = ref(null);

const settlementForm = reactive({
    details: []
});

const rules = {
    settledAmount: [{ required: true, message: '成交金额不能为空', trigger: 'blur' }],
    settledShares: [{ required: true, message: '成交份额不能为空', trigger: 'blur' }],
    fee: [{ required: true, message: '手续费不能为空', trigger: 'blur' }],
    failureReason: [{ required: true, message: '失败原因不能为空', trigger: 'blur' }]
};

const tradeApi = {
    getTradeOrderDetails: (id) => axios.get(`/api/trade/order/${id}`),
    settleTradeOrder: (id, data) => axios.post(`/api/trade/order/${id}/settle`, data),
};

const statusMap = {
    APPROVED: { text: '已批准', type: '' },
    // ... other statuses
};
const getStatusText = (status) => statusMap[status]?.text || status;
const getStatusTag = (status) => statusMap[status]?.type || 'info';

const getFundCodeByDetailId = (detailId) => {
    const detail = order.value.details?.find(d => d.id === detailId);
    return detail ? detail.fundCode : '未知';
};

const goBack = () => {
    router.back();
};

const submitSettlement = () => {
    settlementFormRef.value.validate(async (valid) => {
        if (valid) {
            submitting.value = true;
            try {
                await tradeApi.settleTradeOrder(order.value.id, settlementForm);
                ElMessage.success('订单交割成功！');
                router.push({ name: 'TradeOrderDetail', params: { id: order.value.id } });
            } catch (error) {
                ElMessage.error('交割失败: ' + (error.response?.data?.message || error.message));
            } finally {
                submitting.value = false;
            }
        } else {
            ElMessage.error('请填写所有必填的交割信息。');
        }
    });
};

onMounted(async () => {
    const orderId = route.params.id;
    if (orderId) {
        try {
            const orderRes = await tradeApi.getTradeOrderDetails(orderId);
            order.value = orderRes.data;

            if (order.value.status !== 'APPROVED') {
                ElMessage.warning('只有已批准的订单才能进行交割。');
                router.back();
                return;
            }

            // 初始化表单
            settlementForm.details = order.value.details.map(detail => ({
                orderDetailId: detail.id,
                success: true,
                settledAmount: detail.amount, // 默认等于计划金额
                settledShares: 0,
                fee: 0,
                failureReason: ''
            }));

        } catch (error) {
            ElMessage.error('获取订单详情失败: ' + (error.response?.data?.message || error.message));
        } finally {
            loading.value = false;
        }
    }
});
</script>

<style scoped>
.page-container {
    padding: 20px;
}

.mt-4 {
    margin-top: 1.5rem;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.settlement-item {
    padding: 15px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    margin-bottom: 20px;
}

.settlement-item h4 {
    margin-top: 0;
    margin-bottom: 15px;
}
</style>